/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.sui.bigdata.flink.sql.sink.phoenix;


import com.sui.bigdata.flink.sql.core.sink.IStreamSinkGener;
import com.sui.bigdata.flink.sql.sink.jdbc.JdbcSink;
import com.sui.bigdata.flink.sql.sink.jdbc.format.RetractJDBCOutputFormat;

import java.util.List;
import java.util.Map;

/**
 * Reason:
 * Date: 2019/9/23
 * @author yong_chen@sui.com
 */

public class PhoenixSink extends JdbcSink implements IStreamSinkGener<JdbcSink> {

    private static final String PHOENIX_DRIVER = "org.apache.phoenix.jdbc.PhoenixDriver";

    private static final String UPSERT = "upsert";

    public PhoenixSink() {
    }

    @Override
    public RetractJDBCOutputFormat getOutputFormat() {
        return new RetractJDBCOutputFormat();
    }

    @Override
    public void buildSql(String tableName, List<String> fields,String operation) {
        buildInsertSql(tableName, fields , operation);
    }

    @Override
    public String buildUpdateSql(String tableName, List<String> fieldNames, Map<String, List<String>> realIndexes, List<String> fullField) {
        return null;
    }

    private void buildInsertSql(String tableName, List<String> fields, String operation) {
        String sqlTmp="";
        switch (operation) {
            case UPSERT:
                sqlTmp = "upsert into " + tableName + " (${fields}) values (${placeholder})";
                break;
            default:
                 throw new RuntimeException("Phoenix sink not support "+operation+ " now ");
        }

        String fieldsStr = "";
        String placeholder = "";

        for (String fieldName : fields) {
            fieldsStr += "," + fieldName;
            placeholder += ",?";
        }

        fieldsStr = fieldsStr.replaceFirst(",", "");
        placeholder = placeholder.replaceFirst(",", "");

        sqlTmp = sqlTmp.replace("${fields}", fieldsStr).replace("${placeholder}", placeholder);
        this.sql = sqlTmp;
    }


    @Override
    public String getDriverName() {
        return PHOENIX_DRIVER;
    }


}
